package com.mynetwork.data;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.mynetwork.utils.FileUtils;
import com.mynetwork.utils.SharedPrefHelper;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;


public class ContentManager extends NetworkManager {
	private static final String TAG = "ContentManager";
	protected boolean sIsUpdate = false;
	
	public OnNetworkListener mOnNetworkListener;
	
	public static ContentManager mInstance = null;
	public static ContentManager getInstance() {
		if (mInstance == null) {
			mInstance = new ContentManager();
		}
		return mInstance;
	}
	private ContentManager() {}
	private ArrayList<ContentInfo> mContentList = new ArrayList<ContentInfo>();
	
	public void addContentInfo(ContentInfo info) {
		boolean isExists = false;
		for (ContentInfo i:mContentList) {
			if (i.idx == info.idx) {
				isExists = true;
			}
		}
		
		if (isExists) {
			int count = mContentList.size();
			for (int i=0;i<count;i++) {
				if (mContentList.get(i).idx == info.idx) {
					mContentList.remove(i);
					count = mContentList.size();
					i--;
				}
			}
		}
		mContentList.add(info);
	}

	public ArrayList<ContentInfo> getContentList() {
		return mContentList;
	}
	
	public void clear() {
		mContentList.clear();
	}

	public void addAll(ArrayList<ContentInfo> array) {
		mContentList = array;
	}
	
	public void setJSONObject(JSONObject e) {
		try {
			ContentInfo info = new ContentInfo(e);
			for (int i = 0; i < info.imgUrls.size(); i++) {
				String path = AppData.CONTENT_IMAGE_BACKUP_PATH + info.imgUrls.get(i).substring(info.imgUrls.get(i).lastIndexOf("/"), info.imgUrls.get(i).length());
				info.mIsMainLocalBackup = FileUtils.fileIsLive(path);
			}
			
//			if (info.imgUrls != null) {
//				path = AppData.CONTENT_IMAGE_BACKUP_PATH + info.contDescImgUrl.substring(info.contDescImgUrl.lastIndexOf("/"), info.contDescImgUrl.length());
//				info.mIsDescLocalBackup = FileUtils.fileIsLive(path);
//			}
			mContentList.add(info);
		} catch (JSONException e1) {
			Log.e(TAG, "" + e1);
		}
	}
	
	//[[ Network ------------------------------------------------------------------------
	public void download(Context context, OnNetworkListener l) {
		if (mContentList == null)
			mContentList = new ArrayList<ContentInfo>();
		if (NetworkManager.listCount == 0) {
			clear();
		}
		mUpdateTimeStamp = SharedPrefHelper.getContentInfoListDataTimeStamp(context);
		super.download(context, l);
	}
	
	public void init(Context context) {
		mUpdateTimeStamp = SharedPrefHelper.getContentInfoListDataTimeStamp(context);
	}
	
	public void setPrefTimeStamp(Context context) {
		SharedPrefHelper.setContentInfoListDataTimeStamp(context,mUpdateTimeStamp);
	}
	
	@Override
    public HttpURLConnection getConnection() throws IOException {
    	HttpURLConnection conn = NetworkManager.getUrlConnection(NetworkManager.getApiServerURL() + NetworkManager.CONTENT_INFO_LIST);
		
		StringBuilder strBuilder = NetworkManager.getNetworkDefaultPacket();
//		if (mUpdateTimeStamp > 0 && FileUtils.fileIsLive(AppData.CONTENT_INFO_FILE_PATH))
//			strBuilder.append("&datetime=" + mUpdateTimeStamp);
		Log.e(TAG,"KDS3393_url = " + NetworkManager.getApiServerURL() + NetworkManager.CONTENT_INFO_LIST + strBuilder.toString());
		OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); 
        PrintWriter writer = new PrintWriter(outStream); 
        writer.write(strBuilder.toString()); 
        writer.flush(); 
    	return conn;
    }
	
	@Override
    public boolean jsonParser(JSONObject jsonObj) throws JSONException {
		JSONArray array = jsonObj.getJSONArray("list");
		if (array.length() <= 0) {
			addAll(ContentInfo.ReadInfo(AppData.CONTENT_INFO_FILE_PATH));
			return true;
		}

		FileUtils.deleteFolder(AppData.CONTENT_IMAGE_BACKUP_PATH);
		FileUtils.deleteFile(AppData.CONTENT_INFO_FILE_PATH);
		(new File(AppData.CONTENT_IMAGE_BACKUP_PATH)).mkdirs();
		
        for(int i=0;i < array.length();i++){
        	setJSONObject(array.getJSONObject(i));
        }
        ContentInfo.WriteInfo(AppData.CONTENT_INFO_FILE_PATH, getContentList());
        sIsUpdate = true;
        return true;
    }
	
	@Override
	public void getLocalData(){
		addAll(ContentInfo.ReadInfo(AppData.CONTENT_INFO_FILE_PATH));
	}
	
    public void loadSuccess() {
    };
    public void loadFailed() {
    };
}
